package com.somewater.controller
{
	import com.adobe.serialization.json.JSON;
	import com.somewater.storage.GameUserDef;
	import com.somewater.storage.RoomDef;
	
	import flash.errors.IOError;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;

	/**
	 * 
	 */
	public class RpcHandler
	{
		public const server_url:String = "http://www.balans.ljrate.ru/server/rpc.php";
		
		public static var instance:RpcHandler;
		
		
		public var auth_key:String;
		public var session_id:String;
		public var user_id:String;
		private var network_user_id:String;
		private var social_id:int;
		
		
		public function RpcHandler()
		{
			if(instance)
				throw new Error("Must die");
			else
				instance = this;
		}
		
		
		public static function Initialize(auth_key:String, 
										  session_id:String, 
										  network_user_id:String,
										  social_id:int):void
		{
			new RpcHandler();
			instance.auth_key = auth_key;
			instance.session_id = session_id;
			instance.network_user_id = network_user_id;
			instance.social_id = social_id;
		}
		
		
		public function init(onComplete:Function, onError:Function, sex:int, first_name:String):void
		{
			sendRequest("init", {sex: sex, network_user_id: network_user_id, first_name: first_name}, function(obj:Object):void{
				user_id = obj.profile.user_id;
				auth_key = obj.secret;
				new GameUserDef(obj.profile);
				onComplete && onComplete(obj);
			}, onError);
		}
		
		public function getRooms(onComplete:Function, onError:Function):void
		{
			sendRequest("get_rooms", null,function(obj:Object):void{
				var rooms:Array = new Array();
				for each(var room:Object in obj.rooms){
					rooms.push(new RoomDef(room));
				}
				onComplete && onComplete(rooms);
				
			},onError);
		}
		private function sendRequest(method:String, params:Object = null, onComplete:Function = null, onError:Function = null):void
		{
			var request:URLRequest = new URLRequest(server_url);
			request.method = URLRequestMethod.POST;
			
			if(params == null)
				params = {};
			
			params["action"] = method;
			params["secret"] = auth_key;
			params["social"] = social_id;
			
			if(user_id)
				params["user_id"] = user_id;
			
			request.data = JSON.encode({"data": params});
			
			var loader:URLLoader = new URLLoader();
			loader.addEventListener(Event.COMPLETE, onCompleteHandler);
			loader.addEventListener(IOErrorEvent.IO_ERROR, onErrorHandler);
			loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onErrorHandler);
			
			loader.load(request);
			
			function clearHandlers():void
			{
				loader.removeEventListener(Event.COMPLETE, onCompleteHandler);
				loader.removeEventListener(IOErrorEvent.IO_ERROR, onErrorHandler);
				loader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onErrorHandler);
			}
			
			function onCompleteHandler(e:Event):void
			{
				clearHandlers();
				var response:String = URLLoader(e.target).data;
				if(response == null || response.length == 0)
				{
					onError && onError({errors:"EmptyResponse"});
				}else{
					var json:Object;
					try
					{
						json = JSON.decode(response);
					}catch(e:Error)
					{
						onError && onError({errors:"JSON error"});
					}
					
					if(json)
					{
						onComplete && onComplete(json);
					}
				}
			}
			
			function onErrorHandler(e:Event):void
			{
				clearHandlers();
				if(e is IOErrorEvent)
					onError && onError({errors:"IOerror"});
				else
					onError && onError({errors:"SecureError"});
			}
		}
	}
}